from DrissionPage import ChromiumPage, ChromiumOptions
import os
import re
import json
import time
import random
from DrissionPage.errors import ContextLostError

from chat_dify_blocking import get_text
import pyautogui
from clean_json_1 import process_json_1
from clean_json_2 import process_json_2

co = ChromiumOptions().set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置浏览器路径
co.set_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36')  # 设置 User-Agent
page = ChromiumPage(co)

# 拿到所有商品链接和商品名称
# page.get('https://www.walmart.com/browse/home/freezers/4044_90548_6828819?povid=GlobalNav_rWeb_HomeGardenTools_Appliances_Freezers')
page.get('https://www.walmart.com/browse/home/freezers/4044_90548_6828819?povid=GlobalNav_rWeb_HomeGardenTools_Appliances_Freezers&seo=home&seo=freezers&seo=4044_90548_6828819&page=2&affinityOverride=default')

all_goods = []

# 鼠标右键左滑
def mouse_right():
    # 获取屏幕中心坐标
    screen_width, screen_height = pyautogui.size()
    start_x, start_y = screen_width // 2, screen_height // 2
    end_x = start_x - 100  # 目标点（向左 100 像素）

    # 移动鼠标到屏幕中心
    pyautogui.moveTo(start_x, start_y, duration=0.5)

    # 按住鼠标右键
    pyautogui.mouseDown(button='right')

    # 生成滑动轨迹（曲线/随机波动）
    steps = random.randint(5, 10)  # 随机步数，增加不规律性
    for i in range(steps):
        # 计算当前位置
        curr_x = start_x - ((i + 1) / steps) * 100  # 逐步向左移动
        curr_y = start_y + random.randint(-5, 5)  # Y 方向增加随机抖动
        pyautogui.moveTo(curr_x, curr_y, duration=random.uniform(0.05, 0.15))

    # 释放鼠标右键
    pyautogui.mouseUp(button='right')

# links = page.eles('x://a[contains(@class, "w-100 h-100")]')
links = page.eles('x://div[@class="mb0 ph0-xl pt0-xl bb b--near-white w-25 pb3-m ph1"]')

# for link in links:
for i in range(10,40):
    page.wait(1)
    linkss = page.eles('x://div[@class="mb0 ph0-xl pt0-xl bb b--near-white w-25 pb3-m ph1"]')
    print(i)
    link = linkss[i]

    for i in range(3):
        try:
            name = link.ele('x://span[@class="w_iUH7"]')
            if name:
                # print(name)
                break
        except ContextLostError:
            print("商品名 等待重新加载...")
            time.sleep(1)  # 休息1秒再试


    goods_name = name.text
    print(f"goods_name:{goods_name}")

    # 获取商品详情
    success = False
    for i in range(3):
        try:
            info = link.ele('x://a[@class="w-100 h-100 z-1 hide-sibling-opacity  absolute"]')
            if info:
                success = True
                break

        except ContextLostError:
            print("详情，等待重新加载...")
            time.sleep(1)  # 休息1秒再试

    if success:
        page.run_js('arguments[0].click();', info)

        page.wait(1)

        # 获取所有 li 元素

        for i in range(3):
            try:
                lis = page.eles('x://div[contains(@class, "expand-collapse-content")]//li')
                if lis:
                    break
            except ContextLostError:
                lis = None
                print("描述，等待重新加载...")
                time.sleep(1)  # 休息1秒再试

        # 如果 lis 为空，跳过当前商品，继续下一个
        if lis is None:
            print("未找到描述信息，跳过此商品")
            mouse_right()
            continue

        # 提取文本内容
        li_texts = [li.text for li in lis]

        texts_all = []

        if len(li_texts) > 5:
            for text in li_texts[:5]:
                texts_all.append(text)
        else:
            for text in li_texts:
                texts_all.append(text)

        mouse_right()
        print('返回上一页')

        print(f'texts_all{texts_all}')

        if len(texts_all) != 0:

            # [Selling points]:   ;[target groups]:   ;[usage scenarios]:    .
            # target_text = get_text('Use short sentences to summarize the selling points, target groups, and usage scenarios from this paragraph', texts_all)

            # # print(f'target_text:{target_text}')
            # # 规范格式
            # input = re.sub(r"\*\*Selling Points:\*\s*", "[Selling points]: ", target_text)
            # input = re.sub(r"\*\*Target Groups:\*\s*", "[Target groups]: ", input)
            # input = re.sub(r"\*\*Usage Scenarios:\*\s*", "[Usage scenarios]: ", input)
            # input = re.sub(r"[\n-]+", " ", input)  # 处理换行符和列表项
            #
            # input = input.replace("\\n", "").replace("\\", "")
            #
            # # out_put = get_text('Generate a sales script for this product targeting a US audience of up to 100 words [product]:', goods_name)
            # out_put = get_text('Generate a sales script for this product targeting a US audience [product]:', goods_name)
            # out_put = out_put.replace("\n", "")  # 用空格替换换行符
            #
            # out_put = out_put.replace("\\n", "").replace("\\", "")
            # print(f'out_put:{out_put}')

            goods_dict = {
                'instruction':f'Generate a sales script for [{goods_name}] targeting American audiences',
                'input':f'{texts_all}',
                'output':''
            }
            all_goods.append(goods_dict)
            if len(all_goods) == 10:
                break

            page.wait(5)
            print(goods_dict)
    else:
        print("没有找到匹配的文本")

num = 47


json_file_path = os.path.join(r"D:\subtitle\goods", f'walmart_goods_{num}.json')
with open(json_file_path, 'w', encoding='utf-8') as f:
    json.dump(all_goods, f, ensure_ascii=False, indent=4)

# 清洗数据
# process_json_1(num)   # 特殊字符
# process_json_2(num)   # 大小写与双空格